package org.example.springbootwork.Reflection;

import org.example.springbootwork.domain.User;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test03 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchFieldException {
        Class<?> clazz = Class.forName("org.example.springbootwork.domain.User");

        // 通过Class对象构造其真实类User的对象
        User user = (User) clazz.getDeclaredConstructor().newInstance();

        // 获取setName方法
        Method setNameMethod = clazz.getDeclaredMethod("setName", String.class);
        // 调用setName方法
        setNameMethod.invoke(user, "zhangsan");

        System.out.println(user.getName());
        System.out.println("=================================");

        // 获取age字段
        Field ageField = clazz.getDeclaredField("age");
        ageField.setAccessible(true);
        // 设置age字段的值
        ageField.set(user, 18);
        System.out.println(user.getAge());
    }
}
